#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#include "frame.h"
#include "rf12.h"

static unsigned char frame_buffer[FRAME_BUFFER_SIZE];

//return 0 without success
//return frame length with success

unsigned char receive_frame(unsigned char* data, uint8_t* bytes_received)
{	
	uint16_t crc_ack;
	unsigned char frame_bytes, i;
	unsigned char ACK_msg[ACK_MSG_SIZE];
	CONVERT_STAT crc16;

	cli();

	frame_bytes = rf12_rxdata_crc(frame_buffer, &crc16.w2);

	ACK_msg[1] = crc16.b[0];
	ACK_msg[2] = crc16.b[1];

	if(crc16.w2)
		{
/*
			if(frame_bytes == ACK_MSG_SIZE)
			{
				sei();
				return frame_buffer[0];
			}
*/
			for ( i = 0; i < frame_bytes; i++)
				*data++ = frame_buffer[i];

			ACK_msg[0] = ACK_FRAME_RECEIVED;
			rf12_txdata_crc(ACK_msg, ACK_MSG_SIZE, &crc_ack);

			sei();
			return frame_bytes;
		}
		else
		{
			ACK_msg[0] = NACK_FRAME_RECEIVED;
			rf12_txdata_crc(ACK_msg, ACK_MSG_SIZE, &crc_ack);

			sei();
			return 0x00;
		}


}

unsigned char send_frame(unsigned char* data, uint8_t bytes_to_send)
{	
	
	unsigned char ack_buff[ACK_BUFFER_SIZE];
	uint8_t i = 0;
	uint16_t crc_sended = 0, crc_ack = 0;
	int timeout = TIMEOUT_WAIT_ACK;
	CONVERT_STAT crc_received;

	cli();

	for ( i = 0; i < bytes_to_send; i++)
		frame_buffer[i] = *data++;

	rf12_txdata_crc(frame_buffer, bytes_to_send, &crc_sended);
	
	while(timeout--)
		if(rf12_data())
		{
			i = rf12_rxdata_crc(ack_buff, &crc_ack);

			crc_received.b[0] = ack_buff[1];
			crc_received.b[1] = ack_buff[2];

			if (crc_received.w2 == crc_sended) 
			{	
				sei();
				return ack_buff[0]; //ACK or NACK
			}
		}

	sei();
	return ACK_FRAME_TIMEOUT;
}
